package com.cqrt.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 通用JSON解析工具：将JSON字符串（含嵌套结构）解析为扁平Map
 */
public class JsonToMapUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将JSON字符串解析为Map，支持外层字段和extprop嵌套字段
     * @param jsonStr 原始JSON字符串
     * @return 包含所有key-value的Map（外层字段和extprop字段平级存储）
     */
    public static Map<String, Object> jsonToMap(String jsonStr) {
        Map<String, Object> resultMap = new HashMap<>();
        if (jsonStr == null || jsonStr.trim().isEmpty()) {
            return resultMap;
        }

        try {
            // 解析外层JSON
            JsonNode rootNode = objectMapper.readTree(jsonStr);
            Iterator<Map.Entry<String, JsonNode>> outerFields = rootNode.fields();

            // 处理外层字段
            while (outerFields.hasNext()) {
                Map.Entry<String, JsonNode> entry = outerFields.next();
                String key = entry.getKey();
                JsonNode valueNode = entry.getValue();

                // 如果是extprop字段，解析其内部JSON
                if ("extprop".equals(key)) {
                    String extpropJson = valueNode.asText();
                    if (extpropJson != null && !extpropJson.isEmpty()) {
                        JsonNode extNode = objectMapper.readTree(extpropJson);
                        Iterator<Map.Entry<String, JsonNode>> extFields = extNode.fields();
                        while (extFields.hasNext()) {
                            Map.Entry<String, JsonNode> extEntry = extFields.next();
                            resultMap.put(extEntry.getKey(), extEntry.getValue().asText());
                        }
                    }
                } else {
                    // 普通外层字段直接存入
                    resultMap.put(key, valueNode.asText());
                }
            }

        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON解析失败：" + e.getMessage(), e);
        }

        return resultMap;
    }
}